import { Effect, Reducer, Subscription } from 'umi';
import { parse } from 'query-string';
import { replaceParam } from '../../utils/navigator';

export interface HomeModelState {
  tabKey: string;
}

export interface HomeModelType {
  namespace: 'home';
  state: HomeModelState;
  effects: {
    query: Effect;
  };
  reducers: {
    save: Reducer<HomeModelState>;
    changeTab: Reducer<HomeModelState>;
  };
  subscriptions: { setup: Subscription };
}

const HomeModel: HomeModelType = {
  namespace: 'home',
  state: {
    tabKey: 'home',
  },
  effects: {
    *query({ payload }, { call, put }) {},
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    changeTab(state, action) {
      const { tabKey } = action.payload;
      history.replaceState({}, document.title, replaceParam('tab', tabKey));
      return {
        ...state,
        tabKey,
      };
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, search }) => {
        if (pathname == '/') {
          const result = parse(search);
          dispatch({
            type: 'save',
            payload: {
              tabKey: result.tab || 'home',
            },
          });
        }
      });
    },
  },
};

export default HomeModel;
